﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class ImgManager : MonoSingleton<ImgManager>
{
    public int[] spriteID;
    public float[] timerArr;
    public GameObject imgGo;
    public float timer = 2f;

    private Image image;
    private int curSpriteIdx = 0;
    private float curTime = 0;
    private List<Image> imgList;
    private bool isStartTimeCount = false;

    // Start is called before the first frame update
    void Start()
    {
        imgList = new List<Image>();
        if (spriteID.Length != timerArr.Length)
        {
            Debug.LogError("配置有问题");
        }
        curTime = 0;
        isStartTimeCount = true;
    }

    public override void Release()
    {
        curTime = 0;
        isStartTimeCount = true;
        curSpriteIdx = 0;
        base.Release();
    }

    private void Update()
    {
        if (!isStartTimeCount)
            return;

        if (SceneManager.GetActiveScene().name != "GameApp")
        {
            curTime = 0;
            isStartTimeCount = false;
            return;
        }

        curTime += Time.deltaTime;
        if (curTime >= timerArr[curSpriteIdx])
        {
            GameObject go = GetImageGameObject();
            ImageItem imageItem = go.GetComponent<ImageItem>();
            if (imageItem != null)
            {
                imageItem.transform.localScale = Vector3.one;
                imageItem.transform.SetAsLastSibling();
                go.SetActive(true);
                imageItem.ChangeImage(spriteID[curSpriteIdx]);
                imageItem.ChangeScale(0, timer, ()=> { 
                    go.SetActive(false);
                    int spriteIdx = spriteID[curSpriteIdx];
                    int mapIdx = MapManager.Instance.GetCurrIdx();
                    if (spriteIdx - 1 != mapIdx)
                    {
                        HPManager.Instance.OnPlayerHit();
                    }
                });
                //curTime = 0;
                curSpriteIdx++;
                if (curSpriteIdx >= timerArr.Length)
                    isStartTimeCount = false;
            }
        }
    }

    GameObject GetImageGameObject()
    {
        GameObject go;
        for (int i = 0; i < imgList.Count; i++)
        {
            if (imgList[i] != null && !imgList[i].gameObject.activeSelf)
            {
                go = imgList[i].gameObject;
                return go;
            }
        }

        go = Instantiate(imgGo, imgGo.transform.parent);
        Image image = go.GetComponent<Image>();
        imgList.Add(image);
        return go;
    }
}
